#############################################################################
##
## Copyright (C) 2006-2006 Mindcast Productions. All rights reserved.
##
## This file is part of the Universal SQL Navigator - UniSQLNav.
## Find more information in: http://code.google.com/p/unisqlnav/
## Contact at carlosedp@gmail.com
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file.  Please review the following information to ensure GNU
## General Public Licensing requirements will be met:
## http://www.gnu.org/licenses/gpl.txt
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
## $Rev: $
## $Date: 2006-11-09 11:05:27 -0200 (qui, 09 nov 2006) $
##
#############################################################################

import os
import sys
import cx_Oracle

from utils.utilities import executable_path
from db.backends import DatabaseException, DBQueryError

class Database(object):
    """
    This class provides the methods to access a SQLite database
    """
    
    def __init__(self, db, host, port, user, pwd):
        """
        Create the Database object
        """
        '''
        self.database = os.path.join( executable_path(), db )

        if not os.access( self.database, os.F_OK ):
            msg = ( 'The database file "' + self.database + 
                 '" does not exist' )
            raise DatabaseException( msg )
        if not os.access( self.database, os.R_OK ):
            msg = ( 'The database file "' + self.database + 
                 '" does not have read permissions' )
            raise DatabaseException( msg )
        if not os.access( self.database, os.W_OK ):
            msg = ( 'The database file "' + self.database + 
                 '" does not have write permissions' )
            raise DatabaseException( msg )
        '''
        connstring = user + '/' + pwd + '@' + db
        self.connection = cx_Oracle.connect(connstring)
        self.cursor = self.connection.cursor()
        self.cursor.arraysize = 50
        
    def getTables(self):
        return self.queryAllData('''
            SELECT table_name
            FROM user_tables
            ORDER BY table_name''')

    def getIndexes(self, table):
        return self.queryAllData('''
            SELECT index_name
            FROM user_indexes
            WHERE table_name = :arg_1 
            ORDER BY index_name''',[table,])

    def getTriggers(self, table):
        return self.queryAllData('''
            SELECT trigger_name
            FROM user_triggers
            WHERE table_name = :arg_1
            ORDER BY trigger_name''',[table,])

    def getViews(self):
        return self.queryAllData('''
            SELECT view_name
            FROM user_views
            ORDER BY view_name''')

    def queryAllData(self, query, data=[]):
        """
        Load data from the SQL database and return all rows
        """
        try:
            if query[-1:] == ';':
                query = query[:-1]
            self.cursor.execute(query, data)
            return self.cursor.fetchall()
        except cx_Oracle.DatabaseError, msg:
            raise DBQueryError(msg)

    def queryDataCursor(self, query, data=""):
        """
        Load data from the SQL database and returns the cursor
        """
        try:
            if query[-1:] == ';':
                query = query[:-1]      
            self.cursor.execute(query, data)
            return self.cursor
        except cx_Oracle.DatabaseError, msg:
            raise DBQueryError(msg)
      
    def updateData(self, query, data):
        """
        Updates or inserts data into the database
        """
        try:
            self.cursor.execute(query, data)
        except cx_Oracle.DatabaseError, msg:
            raise DBQueryError(msg)

    def commitData(self):
        """
        Commits the data
        """
        self.connection.commit()

    def rollbackData(self):
        """
        Roll back current transaction
        """
    	self.connection.rollback()

    def closeDatabase(self):
        """
        Closes the database instance
        """
        self.connection.close()